package io.wdb.handler;

import io.wdb.config.AmqpConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

@Component
public class AmqpHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = AmqpConfig.ALARM_QUEUE_NAME, containerFactory = "aRabbitListenerContainerFactory")
    public void process(@Payload byte[] request) {

        String msgstr = new String(request, Charset.forName("UTF-8"));

        logger.debug("AmqpHandler: process {}", msgstr);

        sendTopic(AmqpConfig.MESSAGE_QUEUE_NAME, msgstr);
    }

    private void sendTopic(String routineKey, String msg) {
        try {
            rabbitTemplate.convertAndSend(AmqpConfig.TOPIC_EXCHANGE, routineKey, msg.getBytes(Charset.forName("UTF-8")));
        }
        catch (AmqpException e) {
            logger.error(e.getMessage());
        }
        catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}

